package com.skyline.attraction.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.skyline.attraction.dao.AttractionDao;
import com.skyline.attraction.model.Attraction;
import com.skyline.attraction.service.AttractionService;
import com.skyline.attraction.type.AttractionType;
import com.skyline.attraction.type.SiteType;
import com.skyline.base.exception.NoOperatePermissionException;
import com.skyline.base.exception.NoResourceException;
import com.skyline.base.exception.OperateFailedException;
import com.skyline.base.type.Activity;
import com.skyline.base.type.Authority;
import com.skyline.common.bean.Page;
import com.skyline.user.dao.FanDao;
import com.skyline.user.model.User;
import com.skyline.user.type.IdolType;
import com.skyline.wo.dao.AlbumDao;

@Service("attractionService")
public class AttractionServiceImpl implements AttractionService {

	@Autowired
	private AttractionDao attractionDao;
	@Autowired
	private FanDao fanDao;
	@Autowired
	private AlbumDao albumDao;

	@Value("${album.cover.defaultCover}")
	private String cover;
	@Value("${album.cover.defaultExt}")
	private String ext;
	@Value("${attraction.defaultPortrait}")
	private String defaultPortrait;

	@Override
	public Long discoveryAttraction(User user, Attraction attraction) {
		String country = attraction.getCountry().split("-")[0];
		String province = attraction.getProvince().split("-")[0];
		String[] cityVal = attraction.getCity().split("-");
		String city = cityVal[0];
		String siteId = cityVal[1];

		long attractionId = attractionDao.insertAttraction(attraction.getName(), defaultPortrait,
				attraction.getCategory(), user.getId(), user.getNickname(), user.getPortrait(), user.getEmail(),
				country, province, city, siteId, attraction.getDetailAddress(), attraction.getLatitude(),
				attraction.getLongitude(), attraction.getIntroduction());

		if (attractionId != 0) {
			albumDao.insertAlbumReturnId(attractionId, attraction.getName(), defaultPortrait, "头像相册", "", "",
					Authority.PUBLIC, Activity.UNDELETABLE, cover, ext);
			fanDao.insertFan(attractionId, attraction.getName(), defaultPortrait, user.getId(), user.getNickname(),
					user.getPortrait(), IdolType.ATTRACTION);

		}
		return attractionId;

	}

	@Override
	public void updateAttractionInfo(Attraction attraction, Long adminId) {
		Long attractionId = attraction.getId();
		Attraction oldAttraction = getAttractionForChange(attractionId, adminId);

		String oldName = oldAttraction.getName();
		String name = attraction.getName();
		if (!StringUtils.equals(oldName, name)) {// 如果不同，则需要校验是否同名
			if (isExist(name)) {
				throw new OperateFailedException("对不起，已存在同名景点！");
			}
		}

		AttractionType category = attraction.getCategory();
		String country = attraction.getCountry().split("-")[0];
		String province = attraction.getProvince().split("-")[0];
		String[] cityVal = attraction.getCity().split("-");
		String city = cityVal[0];
		String siteId = cityVal[1];
		Double latitude = attraction.getLatitude();
		Double longitude = attraction.getLongitude();
		String introduction = attraction.getIntroduction();

		boolean infoChanged = false;
		if (!category.equals(oldAttraction.getCategory())) {
			infoChanged = true;
		}
		if (!country.equals(oldAttraction.getCountry())) {
			infoChanged = true;
		}
		if (!province.equals(oldAttraction.getProvince())) {
			infoChanged = true;
		}
		if (!city.equals(oldAttraction.getCity())) {
			infoChanged = true;
		}
		if (!siteId.equals(oldAttraction.getSiteId())) {
			infoChanged = true;
		}
		if (!latitude.equals(oldAttraction.getLatitude())) {
			infoChanged = true;
		}
		if (!longitude.equals(oldAttraction.getLongitude())) {
			infoChanged = true;
		}
		if (!StringUtils.equals(introduction, oldAttraction.getIntroduction())) {
			infoChanged = true;
		}

		if (infoChanged) {
			attractionDao.updateAttraction(attractionId, name, category, country, province, city, siteId,
					attraction.getDetailAddress(), latitude, longitude, introduction);
		}

	}

	@Override
	public void updateAttractionIntroduction(Long attractionId, String introduction, Long adminId) {
		Attraction oldAttraction = getAttractionForChange(attractionId, adminId);
		if (!StringUtils.equals(introduction, oldAttraction.getIntroduction())) {
			attractionDao.updateAttractionIntroduction(attractionId, introduction);
		}
	}

	@Override
	public void updateAttractionPortrait(Long attractionId, String portrait) {
		attractionDao.updateAttractionPortrait(attractionId, portrait);

	}

	@Override
	public void changeAdministrator(Long attractionId, User oldAdministrator, User newAdministrator) {
		attractionDao.updateAttractionAdmin(attractionId, newAdministrator.getId(), newAdministrator.getNickname(),
				newAdministrator.getEmail(), newAdministrator.getPortrait());

	}

	@Override
	public void deleteAttraction(Long attractionId) {
		attractionDao.updateAttractionActivity(attractionId, Activity.DELETED);

	}

	@Override
	public boolean isExist(String attractionName) {
		List<Attraction> list = attractionDao.queryAttractionsByName(attractionName, Activity.NORMAL);
		if (CollectionUtils.isEmpty(list)) {
			return false;
		}
		return true;

	}

	@Override
	public Attraction viewAttraction(Long attractionId, Long viewerId, boolean addVisitCount) {
		Attraction attraction = attractionDao.queryAttractionById(attractionId, Activity.NORMAL);
		if (attraction == null) {
			throw new NoResourceException("不存在ID[" + attractionId + "]的景点，可能该景点已被删除");
		}
		if (addVisitCount && !attraction.getAdminId().equals(viewerId)) {// 管理员不增加浏览量
			attractionDao.updateAttractionVisitNum(attractionId, 1);
		}
		return attraction;
	}

	@Override
	public Attraction getAttractionForChange(Long attractionId, Long adminId) {
		Attraction attraction = attractionDao.queryAttractionById(attractionId, Activity.NORMAL);
		if (attraction == null) {
			throw new NoResourceException("不存在ID[" + attractionId + "]的景点，可能该景点已被删除");
		}
		if (!attraction.getAdminId().equals(adminId)) {
			throw new NoOperatePermissionException("不是景点管理员，无法进行上传头像操作");
		}
		return attraction;
	}

	@Override
	public List<Attraction> findByName(String name, AttractionType type, Activity activity) {
		if (type == null) {
			return attractionDao.queryAttractionsByName(name, Activity.NORMAL);
		}
		return attractionDao.queryAttractionsByNameAndType(name, type, Activity.NORMAL);
	}
	
	public Attraction getNormalAttraction(Long attractionId) {
		Attraction attraction = attractionDao.queryAttractionById(attractionId, Activity.NORMAL);
		if (attraction == null) {
			throw new NoResourceException("不存在ID[" + attractionId + "]的景点，可能该景点已被删除");
		}
		return attraction;
	}

	@Override
	public List<Attraction> listAttractions(String siteId, SiteType siteType, AttractionType type, Page page) {
		if (siteType == null && type == null) {
			return attractionDao.queryAttractions(page, Activity.NORMAL);
		}
		if (siteType == null) {
			return attractionDao.queryAttractionsByType(type, page, Activity.NORMAL);
		}

		int subLen = 9;
		switch (siteType) {
		case COUNTRY:
			subLen = 3;
			break;
		case PROVINCE:
			subLen = 5;
			break;
		case CITY:
			subLen = 7;
			break;

		default:
			break;
		}
		String subSiteId = siteId.substring(0, subLen);

		if (type == null) {
			return attractionDao.queryAttractionsBySiteId(subSiteId, subLen, page, Activity.NORMAL);
		}
		return attractionDao.queryAttractionsBySiteIdAndType(subSiteId, subLen, type, page, Activity.NORMAL);
	}

}
